package com.any.hook.common.exception;

import oracle.jrockit.jfr.jdkevents.ThrowableTracer;

import java.io.PrintWriter;
import java.io.StringWriter;

public class HookException extends RuntimeException {
    private ErrorCode errorCode;
    public HookException(ErrorCode errorCode,String errorMessage){
        super(errorCode.toString()+" - "+ errorMessage);
        this.errorCode=errorCode;
    }
    private HookException(ErrorCode errorCode,String errorMessage,Throwable cause){
        super(errorCode.toString()+" - "+errorMessage+"-"+getMessage(cause));
        this.errorCode=errorCode;
    }
    public static HookException asHookException(ErrorCode errorCode,String message){
        return new HookException(errorCode,message);
    }
    public static HookException asHookException(ErrorCode errorCode,String errorMessage,Throwable cause){
        if(cause instanceof HookException){
            return (HookException) cause;
        }
        return new HookException(errorCode,errorMessage,cause);
    }
    public static HookException asHookException(ErrorCode errorCode,Throwable cause){
        if(cause instanceof HookException){
            return (HookException) cause;
        }
        return new HookException(errorCode,getMessage(cause));
    }
    public ErrorCode getErrorCode(){return this.errorCode;}
    private static String getMessage(Object obj){
        if(obj==null){
            return "";
        }
        if(obj instanceof Throwable){
            StringWriter str=new StringWriter();
            PrintWriter pw=new PrintWriter(str);
            ((Throwable)obj).printStackTrace(pw);
            return  str.toString();
        }else {
            return obj.toString();
        }
    }
}
